package com.java83.shiro.config;


import com.java83.shiro.entity.JsonWebToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器，继承BasicHttpAuthenticationFilter
 * 不需要配置类注解，因为，这个filter直接写完是没有作用的！
 *  需要把它通过配置类的形式，注入到SecurityManager中！
 */
public class ShiroFilter extends BasicHttpAuthenticationFilter {

    /**
     * 我们通常在这里进行全局跨域处理
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        //这里如果为true将直接放行 进入controller请求，不通过shiro的过滤器链
        return super.preHandle(request, response);
    }

    /**
     * 尝试登录，看是否已经登录过了
     * 如果没有登录直接返回401，如果登录成功就尝试subject.login
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //确保一点，判断请求头中有无数据
        if (isLoginAttempt(request,response)) {
            try {
                //如果有数据则尝试登录
                executeLogin(request,response);
            } catch (Exception e) {
                e.printStackTrace();
                response401(request,response);
            }
        }else{
            //s登录尝试失败(账号密码或者token错误)
            //返回401信息 没有登录
            response401(request,response);
        }
        return true;
    }

    /**
     * 登录判断 获取请求头中的数据，如果有，则为true，表示你以及登录过了，然后现在是尝试认证
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //第一套方法：从请求头中获取，userdata，对象 有这个对象则表示可以认证
//        String userdata = request1.getHeader("userdata");
        //第二套方法：从请求头中获取，Authorization，对象 有这个对象则表示可以认证
        String token =request1.getHeader("Authorization");
        if (token != null) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 真正执行登录的地方
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //第一套方法：从请求头中获取，userdata，对象 有这个对象则表示可以认证
//        String userdata = request1.getHeader("userdata");
//        ObjectMapper objectMapper = new ObjectMapper();
//        String decode = URLDecoder.decode(userdata, "UTF-8");
//        //json转对象 获取的rbacManager对象
//        RbacManager rbacManager = objectMapper.readValue(decode, RbacManager.class);
        //第二套方法：从请求头中获取，Authorization，对象 有这个对象则表示可以认证
        String token =request1.getHeader("Authorization");
//        getSubject(request,response) 这个方法 和下面SecurityUtils.getSubject()是一样的
        Subject subject = SecurityUtils.getSubject();
//        subject.login(new UsernamePasswordToken(rbacManager.getAccount(), rbacManager.getPassword()));
        subject.login(new JsonWebToken(token));
        return true;
    }

    /**
     * 如果登录尝试失败，跳转401接口，返回401信息！
     * @param request
     * @param response
     */
    public void response401(ServletRequest request, ServletResponse response){
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
            //请求401接口
        try {
            request1.getRequestDispatcher("/401").forward(request,response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
}
